/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2022-09-19
 * Time:22:11
 */


import java.util.PriorityQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * 实现线程池案例
 * 同样要用到阻塞队列
 */

class MyThreadpool {
    //建立阻塞队列,生产者消费者模型
    //LinkedBlockingDeque自带比较器
    private BlockingQueue<Runnable> queue = new LinkedBlockingDeque<>();

    public void sbmit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
    }

    public MyThreadpool(int m) {
        //构造方法
        // 在构造方法中, 创建出 M 个线程. 负责完成工作.
        for (int i = 0; i < m; i++) {
            Thread t = new Thread(() -> {
                while (true) {
                    try {
                        Runnable runnable = queue.take();
                        runnable.run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();
        }
    }
}

public class TheThreadpool {
    public static void main(String[] args) throws InterruptedException {
        MyThreadpool pool = new MyThreadpool(10);
        for (int i = 0; i < 1000; i++) {
            int taskId = i;
            pool.sbmit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("执行当前任务: " + taskId + " 当前线程: " + Thread.currentThread().getName());
                }
            });
        }
    }
}

